#!/usr/bin/env python

from mxit import handles
import gobject
from blend import constants
import time

class autoAway:

   ignore = False;
   asleep = False;
   sid = None;

   def __init__(self,blend):
      self.blend = blend;

   def stopCaring(self):
      #print "Stop Caring :/";
      if self.sid is not None:
         gobject.source_remove(self.sid);
         self.sid = None;

   def startCaring(self):
      period = self.blend.config.autoAway[1]*60*1000;
      #print "Start Caring ^-^", period;
      self.sid = gobject.timeout_add(period,self.fallAsleep);

   def status(self):
      if self.ignore == True:
         self.ignore = False;
      else:
         self.poke();

   def poke(self):
      if self.ignore == False:
         if self.sid != None:
            gobject.source_remove(self.sid);
            period = self.blend.config.autoAway[1]*60*1000;
            self.sid = gobject.timeout_add(period,self.fallAsleep);
      if self.asleep == True and self.ignore == False:
         # Wake ourselves up
         widget = self.blend.gui.buddyWindow.statusBox;
         pres = constants.C.orderedPresences.index(self.oldPresence);
         widget.set_active(pres);
         self.asleep = False;
         try:
            self.blend.gui.chatWindow.deiconify();
            self.blend.gui.buddyWindow.deiconify();
         except:
            pass;

   def fallAsleep(self):
      self.ignore = True;

      widget = self.blend.gui.buddyWindow.statusBox;
      model = widget.get_model();
      iter = widget.get_active_iter();
      p = constants.C.presences[handles.Presence.AWAY];
      pres = constants.C.orderedPresences.index(p);
      self.oldPresence = constants.C.presences[handles.Presence.byid(model.get_value(iter,2))];
      widget.set_active(pres);
      
      self.asleep = True;
      try:
         self.blend.gui.chatWindow.iconify();
         self.blend.gui.buddyWindow.iconify();
      except:
         pass;

      return False; # We don't want it to away us again :P
